package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import io.xxx.xbutler.data.TagMapper;
import io.xxx.xbutler.domain.Callback;
import io.xxx.xbutler.domain.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 设置好友标签回调
 *
 * <pre>
 * {
 *     "nType": 2005,
 *     "vcMerchantNo": "",
 *     "vcRobotWxId": "",
 *     "vcRobotSerialNo": "",
 *     "vcSerialNo": "",
 *     "nResult": 1,
 *     "vcResult": "SUCCESS",
 *     "Data": {
 *         "vcFriendSerialNo": "",
 *         "vcFriendWxId": "",
 *         "Tags": [
 *             {
 *                 "nTagId": 1,
 *                 "vcTagName": "",
 *                 "vcBase64TagName": ""
 *             }
 *         ]
 *     }
 * }
 * </pre>
 */
@Slf4j
@Component
public class _2005Handler implements CallbackHandler {

    @Resource
    private TagMapper tagMapper;

    @Override
    public String name() {
        return "设置好友标签回调";
    }

    @Override
    public boolean supports(int type) {
        return type == 2005;
    }

    @Override
    public void handle(Callback callback) {
        LocalDateTime now = LocalDateTime.now();
        JSONObject data = (JSONObject) callback.getData();
        JSONArray tags = data.getJSONArray("Tags");
        for (Object o : tags) {
            JSONObject info = JSONObject.from(o);
            Tag tag = new Tag()
                    .setId(info.getLong("nTagId"))
                    .setName(info.getString("vcTagName"))
                    .setBase64Name(info.getString("vcBase64TagName"))
                    .setContactId(info.getString("vcFriendWxId"))
                    .setContactSerialNo(info.getString("vcFriendSerialNo"))
                    .setCreatedTime(now)
                    .setUpdatedTime(now);
            tagMapper.insertOrUpdate(tag);
        }
    }
}
